//
//  AppDelegate.swift
//  IDF
//
//  Created by 陈徐挺 on 22/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import CYLTabBarController
import YYCategories
import SVProgressHUD
import FDFullscreenPopGesture
import UserNotifications
import YYCache




@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        IQKeyboardManager.sharedManager().enable = true
        UIApplication.shared.setStatusBarHidden(false, with: .none)
        UIApplication.shared.statusBarStyle = .lightContent
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.makeKeyAndVisible()
        appWindow = window!
        SVProgressHUD.setDefaultStyle(.dark)
        SVProgressHUD.setDefaultMaskType(.clear)
        let navBar = UINavigationBar.appearance()
        navBar.barTintColor = UIColor(hexString: "#5784e6")
        navBar.tintColor = UIColor(hexString: "#ffffff")
        navBar.titleTextAttributes = [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 19), NSAttributedStringKey.foregroundColor: UIColor.white]
        setupViewControllers()
        
        window?.rootViewController = mainTabBarController

        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                UNAuthorizationOptions.badge.rawValue |
                UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
        } else if #available(iOS 8.0, *) {
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
        }
        
        #if DEBUG
            JPUSHService.setup(withOption: launchOptions,
                           appKey: "009613bc5c3f67a9e593ce71",
                           channel: "app store",
                           apsForProduction: false)
        #else
            JPUSHService.setup(withOption: launchOptions,
                           appKey: "009613bc5c3f67a9e593ce71",
                           channel: "app store",
                           apsForProduction: true)
        #endif
        login()
        
        JPUSHService.registrationIDCompletionHandler { (resCode, registrationID) in
            if let userId = appUser.userId, let id = registrationID {
                syncUserRegistration(id)
            }
            if let id = registrationID {
                registrationId = id
            }
            
        }
       
        return true
    }
    
    func login() {
        let cache = YYCache(name: "appcache")
        if appLogined {
            return
        }
        if let user = cache?.object(forKey: "appUser") as? User  {
            appUser = user
            let _ = appUser.login().then { _ -> Void in
                let cache = YYCache(name: "appcache")
                cache?.setObject(appUser, forKey: "appUser")
                appLogined = true
                initAliyun()
                if registrationId != "" {
                    syncUserRegistration(registrationId)
                }
                
                }.catch {[weak self] _ in
                    cache?.removeAllObjects()
            }
        } else {
            appUser = User()
            let cache = YYCache(name: "appcache")
            cache?.removeAllObjects()
        }
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
    }  
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
        
        if #available(iOS 10.0, *){
  
        } else {
            UIApplication.shared.applicationIconBadgeNumber = 0
            appWindow.subviews.forEach { (view) in
                if view.isMember(of: LaunchView.self) {
                    view.removeFromSuperview()
                }
            }
            mainTabBarController.selectedIndex = 1
            nowNavgationController = mainTabBarController.viewControllers![1] as! UINavigationController
        }
        
    }
    

    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        UIApplication.shared.applicationIconBadgeNumber = 0
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

// MARK: - tabBar , NavBar 设置

extension AppDelegate: UITabBarControllerDelegate {
    fileprivate func setupViewControllers()  {
        let firstNavVC = initViewContollerWithStoryboard(storyboardName: "Home", storyboardId: "homeNav") as! UINavigationController
        let secondNavVC = initViewContollerWithStoryboard(storyboardName: "Record", storyboardId: "recordNav") as! UINavigationController
        let thirdNavVC = initViewContollerWithStoryboard(storyboardName: "Mine", storyboardId: "mineNav") as! UINavigationController
        
        let dic1 = [CYLTabBarItemTitle: "Home", CYLTabBarItemImage: "home", CYLTabBarItemSelectedImage: "home-select"]
        let dic2 = [CYLTabBarItemTitle: "Record", CYLTabBarItemImage: "record", CYLTabBarItemSelectedImage: "record-select"]
        let dic3 = [CYLTabBarItemTitle: "Mine", CYLTabBarItemImage: "mine", CYLTabBarItemSelectedImage: "mine-select"]

        
        let tabBarController = CYLTabBarController()
        tabBarController.tabBarItemsAttributes = [dic1, dic2, dic3]
        tabBarController.viewControllers = [firstNavVC, secondNavVC, thirdNavVC]
        mainTabBarController = tabBarController
        nowNavgationController = firstNavVC
        mainTabBarController.delegate = self
        mainTabBarController.tabBar.tintColor = UIColor(hexString: "5784e6")
    }
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        /**
         *  设置当前的导航控制器
         */
        nowNavgationController = viewController as! UINavigationController
    }
    
}


extension AppDelegate : JPUSHRegisterDelegate{
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter willPresent");
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))// 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter didReceive");
        let userInfo = response.notification.request.content.userInfo
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
            UIApplication.shared.applicationIconBadgeNumber = 0
            appWindow.subviews.forEach { (view) in
                if view.isMember(of: LaunchView.self) {
                    view.removeFromSuperview()
                }
            }
            mainTabBarController.selectedIndex = 1
            nowNavgationController = mainTabBarController.viewControllers![1] as! UINavigationController
        }
        completionHandler()
    }
}

